package com.its.common.nacos;

import com.alibaba.cloud.nacos.registry.NacosServiceRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author xiaxp
 * @Date 2021-12-21 22:25
 * @Description
 */
@Slf4j
@AutoConfigureAfter({NacosServiceRegistry.class})
public class NacosRegisteredListener implements SmartInitializingSingleton {
    @Value("${spring.application.name}")
    private String appName;

    @Autowired
    DiscoveryClient discoveryClient;

//    @Autowired
//    NacosServiceRegistry nacosServiceRegistry;
//
//    @Autowired
//    NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void afterSingletonsInstantiated() {
        /*
        String serviceName = appName;
        NamingService namingService = NamingFactory.createNamingService(nacosDiscoveryProperties.getServerAddr());
        List<Instance> instances = namingService.getAllInstances(serviceName);
        for (Instance instance : instances) {
            if (instance.getIp().equalsIgnoreCase(nacosDiscoveryProperties.getIp())
                    && instance.getPort() == nacosDiscoveryProperties.getPort()) {
                // instance.isEnabled() ? "UP" : "DOWN";
            }
        }
        */

        new Thread(()->{
            AtomicInteger cnt = new AtomicInteger(0);
            while (cnt.get() < 30){
                cnt.incrementAndGet();
                if(searchNacosService()){
                    break;
                }
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                }
            }
            if(cnt.get() < 30){
                log.info(">>>>>>>>>>>>>>>>> "+ appName +" 服务注册: 成功! >>>>>>>>>>>>>>>>>");
            }else{
                log.error(">>>>>>>>>>>>>>>>> "+ appName +" 服务注册: 未检测到! >>>>>>>>>>>>>>>>>");
            }
        }).start();
    }

    private boolean searchNacosService() {
        try {
            List<String> services = discoveryClient.getServices();
            if(null == services || services.isEmpty()){
                return false;
            }
            for (String service : services) {
                if(Objects.equals(service,appName)){
                    return true;
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }
}
